package bb.lanxing.lib.devices.sprint.model.impl;

import android.content.Context;
import android.util.Log;
import androidx.collection.LongSparseArray;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
//import com.igexin.push.f.r;
import bb.lanxing.lib.devices.core.sync.DeviceFileStatus;
import bb.lanxing.lib.devices.core.utils.DeviceHelper;
import bb.lanxing.lib.devices.sprint.entity.SprintMaps;
import bb.lanxing.lib.devices.sprint.model.SprintMapModel;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public abstract class AbstractSprintMapModel implements SprintMapModel {
    protected static final String MAP_JSON_URL = "http://cdn.bi-ci.com/MapResources/map_list.json";
    protected static final String STATIC_MAP_LIST = "sprint_maps.json";
    private static OkHttpClient client;
    private LongSparseArray<SprintMaps> cacheMaps;
    protected SprintMapModel.Callback callback;
    protected Context context;
    private LongSparseArray<Subscription> downloadSubs;
    private List<SprintMaps> sprintMaps;

    public String getServerMapUrl() {
        return MAP_JSON_URL;
    }

    @Override
    public boolean syncWithDevice(SprintMaps sprintMaps) {
        return false;
    }

    public AbstractSprintMapModel(Context context) {
        this.context = context;
    }

    @Override
    public void setCallback(SprintMapModel.Callback callback) {
        this.callback = callback;
    }

    @Override
    public boolean downloadMapById(final long j) {
        if (isDownloading(j)) {
            return false;
        }
        notifyMapsStatus(j, DeviceFileStatus.STATUS_DOWNLOADING);
        Subscription subscribe = Observable.create(new Observable.OnSubscribe<Integer>() {
            @Override
            public void call(Subscriber<? super Integer> subscriber) {
                SprintMaps sprintMapById = AbstractSprintMapModel.this.getSprintMapById(j);
                String path = AbstractSprintMapModel.this.getPath(sprintMapById.getId());
                File file = new File(path + ".tmp");
                try {
                    Response execute = AbstractSprintMapModel.createHttpClient().newCall(new Request.Builder().url(sprintMapById.getUrl()).get().build()).execute();
                    if (execute.isSuccessful()) {
                        ResponseBody body = execute.body();
                        long contentLength = body.contentLength();
                        InputStream byteStream = body.byteStream();
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        byte[] bArr = new byte[4096];
                        float f = 0.0f;
                        int i = -1;
                        while (true) {
                            int read = byteStream.read(bArr);
                            if (read == -1) {
                                break;
                            }
                            fileOutputStream.write(bArr, 0, read);
                            f += read;
                            int i2 = (int) ((f / ((float) contentLength)) * 100.0f);
                            if (i != i2) {
                                subscriber.onNext(i2);
                            }
                            i = i2;
                        }
                        fileOutputStream.close();
                        byteStream.close();
                        body.close();
                        file.renameTo(new File(path));
                    }
                    subscriber.onCompleted();
                } catch (IOException e) {
                    subscriber.onError(e);
                }
            }
        }).buffer(1000L, TimeUnit.MILLISECONDS).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
            @Override
            public void onCompleted() {
                AbstractSprintMapModel.this.notifyMapsStatus(j, DeviceFileStatus.STATUS_DOWNLOADED);
            }

            @Override
            public void onError(Throwable th) {
                AbstractSprintMapModel.this.notifyMapsStatus(j, DeviceFileStatus.STATUS_DOWNLOAD_FAIL);
            }

            @Override
            public void onNext(List<Integer> list) {
                if (!list.isEmpty()) {
                    AbstractSprintMapModel.this.notifyProgressUpdate(j, list.get(0));
                }
            }
        });
        if (this.downloadSubs == null) {
            this.downloadSubs = new LongSparseArray<>();
        }
        this.downloadSubs.put(j, subscribe);
        return true;
    }

    @Override
    public boolean isDownloaded(long j) {
        File createFile;
        SprintMaps sprintMapById = getSprintMapById(j);
        return (sprintMapById == null || (createFile = createFile(sprintMapById)) == null || !createFile.exists()) ? false : true;
    }

    @Override
    public boolean isDownloading(long j) {
        LongSparseArray<Subscription> longSparseArray = this.downloadSubs;
        Subscription subscription = longSparseArray != null ? longSparseArray.get(j) : null;
        return subscription != null && !subscription.isUnsubscribed();
    }

    @Override
    public boolean isSynced(long j) {
        File createFile = createFile(getSprintMapById(j));
        return createFile != null && createFile.exists();
    }

    protected boolean hasMap(long j) {
        LongSparseArray<SprintMaps> longSparseArray = this.cacheMaps;
        return (longSparseArray == null || longSparseArray.get(j) == null) ? false : true;
    }

    public List<SprintMaps> loadSprintMapsFromServer() throws IOException, JSONException {
        Response execute = createHttpClient().newCall(new Request.Builder().url(getServerMapUrl()).get().build()).execute();
        if (execute.isSuccessful()) {
            String string = null;
            if (execute.body() != null) {
                string = execute.body().string();
            }
            File file = new File(getWorkDir(), STATIC_MAP_LIST);
            BufferedSource buffer = Okio.buffer(Okio.source(new ByteArrayInputStream(string.getBytes())));
            BufferedSink buffer2 = Okio.buffer(Okio.sink(file));
            buffer.readAll(buffer2);
            buffer.close();
            buffer2.close();
            return new GsonBuilder().create().fromJson(
                    new JSONObject(string).getJSONArray("continent").toString(), new TypeToken<List<SprintMaps>>() {}.getType());
        }
        return null;
    }


    public List<SprintMaps> loadSprintMapsFromFile() throws IOException, JSONException {
        String readString;
        File file = new File(getWorkDir(), STATIC_MAP_LIST);
        Gson create = new GsonBuilder().create();
        if (file.exists()) {
            BufferedSource buffer = Okio.buffer(Okio.source(file));
            readString = buffer.readString(StandardCharsets.UTF_8/*Charset.forName(r.b)*/);
            buffer.close();
        } else {
            BufferedSource buffer2 = Okio.buffer(Okio.source(this.context.getAssets().open(STATIC_MAP_LIST)));
            readString = buffer2.readString(StandardCharsets.UTF_8/*Charset.forName(r.b)*/);
            buffer2.close();
        }
        if (readString == null) {
            throw new FileNotFoundException("No such file : sprint_maps.json");
        }
        JSONArray jSONArray = new JSONObject(readString).getJSONArray("continent");
        Log.d("loadSprintMapsFromFile", "loadSprintMapsFromFile: " + jSONArray.toString());
        return create.fromJson(jSONArray.toString(), new TypeToken<List<SprintMaps>>() {}.getType());
    }

    @Override
    public SprintMaps getSprintMapById(long j) {
        LongSparseArray<SprintMaps> longSparseArray = this.cacheMaps;
        if (longSparseArray != null) {
            return longSparseArray.get(j);
        }
        return null;
    }

    @Override
    public SprintMaps getSprintMapByName(String str) {
        if (str == null) {
            return null;
        }
        int size = this.cacheMaps.size();
        for (int i = 0; i < size; i++) {
            LongSparseArray<SprintMaps> longSparseArray = this.cacheMaps;
            SprintMaps sprintMaps = longSparseArray.get(longSparseArray.indexOfKey(i));
            if (sprintMaps != null && str.equals(sprintMaps.getName())) {
                return sprintMaps;
            }
        }
        return null;
    }

    @Override
    public SprintMaps getSprintMapByEnglishName(String str) {
        if (str == null) {
            return null;
        }
        int size = this.cacheMaps.size();
        for (int i = 0; i < size; i++) {
            LongSparseArray<SprintMaps> longSparseArray = this.cacheMaps;
            SprintMaps sprintMaps = longSparseArray.get(longSparseArray.indexOfKey(i));
            if (sprintMaps != null && str.equals(sprintMaps.getNameEn())) {
                return sprintMaps;
            }
        }
        return null;
    }

    @Override
    public void deleteById(long j) {
        LongSparseArray<SprintMaps> longSparseArray = this.cacheMaps;
        if (longSparseArray == null || longSparseArray.size() <= 0) {
            return;
        }
        if (getSprintMapById(j) != null) {
            this.cacheMaps.remove(j);
        }
        notifyMapsStatus(j, DeviceFileStatus.STATUS_DELETED);
    }

    @Override
    public void release() {
        this.callback = null;
        this.context = null;
        if (this.downloadSubs != null) {
            for (int i = 0; i < this.downloadSubs.size(); i++) {
                LongSparseArray<Subscription> longSparseArray = this.downloadSubs;
                Subscription subscription = longSparseArray.get(longSparseArray.indexOfKey(i));
                if (subscription != null) {
                    subscription.unsubscribe();
                }
            }
            this.downloadSubs.clear();
        }
    }

    @Override
    public List<SprintMaps> getSprintMaps() {
        return this.sprintMaps;
    }

    public void setSprintMaps(List<SprintMaps> list) {
        this.sprintMaps = list;
        if (list != null) {
            this.cacheMaps = new LongSparseArray<>();
            for (SprintMaps sprintMaps : list) {
                buildMapCache(sprintMaps, this.cacheMaps);
            }
            return;
        }
        LongSparseArray<SprintMaps> longSparseArray = this.cacheMaps;
        if (longSparseArray == null) {
            return;
        }
        longSparseArray.clear();
    }

    private void buildMapCache(SprintMaps sprintMaps, LongSparseArray<SprintMaps> longSparseArray) {
        List<SprintMaps> maps = sprintMaps.getMaps();
        longSparseArray.put(sprintMaps.getId(), sprintMaps);
        if (maps != null) {
            for (SprintMaps sprintMaps2 : maps) {
                buildMapCache(sprintMaps2, longSparseArray);
            }
        }
    }

    public void notifyMapsStatus(long j, DeviceFileStatus deviceFileStatus) {
        SprintMapModel.Callback callback = this.callback;
        if (callback != null) {
            callback.onMapStatus(j, deviceFileStatus.getStatus());
        }
    }

    public void notifyProgressUpdate(long j, float f) {
        SprintMapModel.Callback callback = this.callback;
        if (callback != null) {
            callback.onProgressUpdate(j, f);
        }
    }

    @Override
    public String getPath(long j) {
        File createFile = createFile(getSprintMapById(j));
        if (createFile != null) {
            return createFile.getAbsolutePath();
        }
        return null;
    }

    protected String getWorkDir() {
        return DeviceHelper.getWorkDir(9);
    }

    public File createFile(SprintMaps sprintMaps) {
        if (sprintMaps == null) {
            return null;
        }
        String workDir = getWorkDir();
        return new File(workDir, sprintMaps.getId() + "_V" + sprintMaps.getVersion() + ".map");
    }

    protected static OkHttpClient createHttpClient() {
        OkHttpClient okHttpClient = client;
        if (okHttpClient != null) {
            return okHttpClient;
        }
        OkHttpClient build = new OkHttpClient.Builder()
                .connectTimeout(5000L, TimeUnit.MILLISECONDS).readTimeout(5000L, TimeUnit.MILLISECONDS).build();
        client = build;
        return build;
    }
}
